<template>
  <div>
    <div class="search-box">
      <el-form inline class="flex items-center" @submit.native.prevent>
        <el-form-item>
          <el-input
            v-model="rowUniqueKeyLike"
            size="small"
            :placeholder="$t('flyparam.entry_label')"
            @keyup.native.enter="fetchReferenceEntryRecord"
            @blur="rowUniqueKeyLike = rowUniqueKeyLike.trim()"
          />
        </el-form-item>
        <el-form-item>
          <el-tooltip :content="$t('page.search')" placement="top">
            <el-button
              type="primary"
              class="align-middle p-1.5"
              size="small"
              @click="
                () => {
                  pageNo = 1
                  fetchReferenceEntryRecord()
                }
              "
            >
              <svg-icon icon-class="search" class="text-lg" />
            </el-button>
          </el-tooltip>
        </el-form-item>
        <el-form-item v-permission="{ permission: PERMISSIONS.DESIGN }">
          <el-tooltip :content="$t('flyparam.new_entry')" placement="top">
            <el-button
              size="small"
              type="primary"
              class="align-middle p-1.5"
              @click="() => (dialogVisible = true)"
            >
              <svg-icon icon-class="plus" class-name="text-lg" />
            </el-button>
          </el-tooltip>
        </el-form-item>
        <el-form-item>
          <el-tooltip
            :content="$t('common.import') + '/' + $t('common.export')"
            placement="top"
          >
            <el-button
              native-type="button"
              size="medium"
              class="p-1.5 align-middle inline-block"
              type="primary"
              @click="importExportVisible = true"
            >
              <svg-icon icon-class="import-export" class-name="form-icon" />
            </el-button>
          </el-tooltip>
        </el-form-item>

        <!--        <el-form-item v-permission="{ permission: PERMISSIONS.DESIGN }">
          <el-tooltip :content="$t('flyparam.batch_operation')" placement="top">
            <el-button size="medium" class="align-middle p-1.5" type="primary" @click="() => (dryrunVisible = true)">
              <svg-icon icon-class="dryrun" class-name="text-lg" />
            </el-button>
          </el-tooltip>
        </el-form-item>-->
      </el-form>
    </div>
    <el-card
      :body-style="{ padding: '0', boderRadius: 0, border: 'none' }"
       
      shadow="never"
      :current-page="pageNo"
      :page-size="pageSize"
      :total="total"
      @current-change="currentChangeHandle"
    >
      <el-table
        ref="table"
        v-loading="loading"
        :data="tableData"
        :row-key="
          (row) => {
            return row.$label
          }
        "
      >
        <el-table-column
          v-for="col in columns"
          :key="col.key"
          :label="col.label"
          :prop="col.key"
        />
        <el-table-column
          :label="$t('page.operation')"
          align="center"
          fixed="right"
          width="100"
        >
          <template v-slot="scope">
            <el-dropdown
              placement="bottom-start"
              @command="(command) => handleDropDownCommand(command, scope.row)"
            >
              <span class="el-dropdown-link">
                <svg-icon icon-class="menu" style="font-size: 24px" />
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-permission="{
                      permission: [
                        PERMISSIONS.CONFIGURATION,
                        PERMISSIONS.DESIGN
                      ]
                    }"
                    command="edit"
                    icon="el-icon-edit"
                  >
                    <span>{{ $t('flyparam.edit') }}</span>
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-permission="{ permission: PERMISSIONS.DESIGN }"
                    command="copy"
                    icon="el-icon-document-copy"
                  >
                    <span>{{ $t('flyparam.copy') }}</span>
                  </el-dropdown-item>
                  <el-dropdown-item command="compare" icon="el-icon-guide">
                    <span>{{ $t('flyparam.compare') }}</span>
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-permission="{ permission: PERMISSIONS.DESIGN }"
                    command="delete"
                    icon="el-icon-delete"
                  >
                    <span>{{ $t('common.delete') }}</span>
                  </el-dropdown-item>
                </el-dropdown-menu></template
              >
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <new-entry
      :title="$t('flyparam.new_entry')"
      v-model="dialogVisible"
      v-bind="$attrs"
      :table-id="tableId"
      :table-type="tableType"
      :template-id="templateId"
      @save="(rowUniqueKey) => handleNewEntry(rowUniqueKey)"
    />

    <edit-entry
      :title="$t('page.edit')"
      v-bind="$attrs"
      :template-id="templateId"
      :table-id="tableId"
      :table-type="tableType"
      v-model="editEntryVisible"
      :entity-id="entityId"
      :entity-name="entityName"
      :entity-value="entityValue"
      @save="fetchReferenceEntryRecord"
    />
    <parameter-edit-dialog
      v-bind="$attrs"
      type="refTable"
      v-model="parameterDialogVisible"
      :table-id="tableId"
      :entity-name="entityName"
      :sn-label="entityName"
      :form="$refs.entryForm"
      :template-id="templateId"
      @save="handleEditConfirm"
    />
    <import-export-dialog
      :authorized="$store.getters.btnPermissions.includes(PERMISSIONS.DESIGN)"
      v-model="importExportVisible"
      v-bind="$attrs"
      type="Reference"
      :tree-data="treeData"
      :table-id="tableId"
      :template-id="templateId"
      :table-type="tableType"
      @requested="fetchReferenceEntryRecord"
    />
    <copy-dialog
      entry-list="true"
      type="entry"
      :title="$t('flyparam.copy_entry')"
      v-model="copyDialogVisible"
      :terminal="terminal"
      @confirm="fetchReferenceEntryRecord"
    />

    <compare-dialog
      is-ref-table
      :template-id="templateId"
      v-model="compareDialogVisible"
      :table-id="tableId"
      :entity-id="entityId"
      :compare-name="compareName"
    />

    <dryrun
      :reference-table="profileTables"
      v-model="dryrunVisible"
      :profile-id="tableId"
      :profile-table-list="profileTables.filter((_) => _.id === tableId)"
      @confirm="
        () => {
          pageNo = 1
          fetchReferenceEntryRecord()
        }
      "
    />

    <task-download v-model="taskDownloadVisible" />
  </div>
</template>

<script>
import NewEntry from './new-entry.vue'
import Dryrun from './dryrun.vue'
import { getReferenceEntryRecord, deleteEntry } from '@/api/parameter'
import ParameterEditDialog from './parameter-edit-dialog.vue'
import { isObjectArray, isObjectBoolean } from '@/utils'
import CopyDialog from './copy-dialog.vue'
import CompareDialog from './compare-dialog.vue'
import TaskDownload from './task-download.vue'
import ImportExportDialog from './import-export-dialog.vue'
import { PERMISSIONS } from '@/components/common/const'
import { types } from '../constant.js'

export default {
  components: {
    NewEntry,
    EditEntry: NewEntry,
    ParameterEditDialog,
    ImportExportDialog,
    CopyDialog,
    CompareDialog,
    Dryrun,
    TaskDownload
  },
  props: {
    tableId: {
      type: String
    },
    tableType: {
      type: Number
    },
    templateId: String
  },
  data() {
    return {
      types: Object.freeze(types),
      PERMISSIONS: { ...Object.freeze(PERMISSIONS.FLY_PARAM) },
      taskDownloadVisible: false,
      dialogVisible: false,
      editEntryVisible: false,
      dryrunVisible: false,
      parameterDialogVisible: false,
      copyDialogVisible: false,
      rowUniqueKeyLike: '',
      terminal: {},
      loading: false,
      tableData: [],
      entityId: '',
      compareName: '',
      columns: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      entityName: '',
      entityValue: '',
      importExportVisible: false,
      compareDialogVisible: false,
      treeData: []
    }
  },
  computed: {
    profileTables() {
      return this.$store.state.parameter.profileTables
    },
    templateInfo() {
      return this.$store.state.parameter.templateInfo
    },
    profileId() {
      if (this.templateInfo) {
        return this.profileTables.find(
          (_) => _.id === this.templateInfo.entryId
        ).id
      }
      return ''
    }
  },
  mounted() {
    this.mounted = true
    // TODO 这个接口被同时调用多次
    this.fetchReferenceEntryRecord()
  },
  methods: {
    fetchReferenceEntryRecord() {
      return new Promise((resolve, reject) => {
        this.loading = true
        this.treeData = []
        this.treeData.push({
          id: this.tableId,
          name: this.$attrs.sn,
          tableType: this.tableType
        })
        this.rowUniqueKeyLike = this.rowUniqueKeyLike.trim()
        getReferenceEntryRecord(this.templateId, this.tableId, {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          rowUniqueKeyLike: this.rowUniqueKeyLike
        })
          .then((data) => {
            this.total = data.total
            this.columns = data.columns.filter((col) => col.key !== '$id')
            this.tableData = data.items.map((item) => {
              const keys = Object.keys(item)
              const ret = {}
              for (let i = 0; i < keys.length; i++) {
                const key = keys[i]
                if (isObjectBoolean(item[key][0])) {
                  ret[key] = item[key][0] + ''
                } else if (isObjectArray(item[key])) {
                  ret[key] = item[key].join()
                } else {
                  ret[key] = item[key][0]
                }
              }
              return ret
            })

            resolve()
          })
          .catch((err) => {
            this.$message.error(err)
            reject(err)
          })
          .finally(() => {
            this.loading = false
          })
      })
    },
    currentChangeHandle(val) {
      this.pageNo = val
      this.fetchReferenceEntryRecord()
    },
    edit(row) {
      if (this.tableType === 2) {
        this.parameterDialogVisible = true
      } else {
        this.editEntryVisible = true
        this.entityValue = row.Value
        this.entityId = row.$id
      }
      this.entityName = row.$label
    },
    handleEditConfirm(params) {
      this.fetchReferenceEntryRecord()
    },
    async handleNewEntry(rowUniqueKey) {
      await this.fetchReferenceEntryRecord()
      if (this.tableType === 2) {
        this.entityName = rowUniqueKey
        this.parameterDialogVisible = true
      }
    },
    copy(row) {
      this.copyDialogVisible = true
      this.terminal.paramsTemplateId = this.templateId
      this.terminal.tableSchemaId = this.tableId
      this.terminal.id = row.$id
    },
    delete(row) {
      this.$commonConfirm({
        title: this.$t('flyparam.delete_entry_title'),
        type: 'danger',
        content: this.$t('flyparam.delete_entry_warning', { label: row.label }),
        btnSureTitle: this.$t('common.delete'),
        onConfirm: (instance, done) => {
          instance.loading = true
          deleteEntry(this.templateId, this.tableId, row.$id)
            .then((res) => {
              this.$message.success(this.$t('page.delete_success'))
              done()
              this.fetchReferenceEntryRecord()
            })
            .catch((e) =>
              this.$confirmError(e).then(() => {
                done()
              })
            )
        }
      })
    },
    compare(row) {
      this.compareDialogVisible = true
      this.entityId = row.$id
      this.compareName = row.$label
    },
    handleDropDownCommand(command, row) {
      this[command](row)
    }
  }
}
</script>

<style lang='scss' scoped>
@import '@/styles/mixin.scss';

::v-deep {
  .el-form-item {
    @include formIcon;
  }
}
</style>
